﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DAL;
using Model;

namespace BLL
{
    public class ProductBLL
    {
        ProductDAL productDAL = new ProductDAL();
        ProductCategoryDAL pcDAL = new ProductCategoryDAL();
        ProductKeyDAL pkDAL = new ProductKeyDAL();

        public void Save(List<ProductListView> list)
        {
            ProductCategory pc = null;
            ProductKey pk = null;

            list.ForEach(x =>
            {
                Save(x);
            });
        }

        public void Save(ProductListView x)
        {
            ProductCategory pc = null;
            ProductKey pk = null;

            if (x.ID == 0)
            {
                productDAL.Insert(x);
            }
            else
            {
                productDAL.Update(x);
                pcDAL.DeleteAllByPID(x.ID);
                pkDAL.DeleteAllByPID(x.ID);
            }
            if (x.CategoryList != null)
            {
                var categorys = x.CategoryList.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string cid in categorys)
                {
                    pc = new ProductCategory { PID = x.ID, CID = int.Parse(cid) };
                    pcDAL.Insert(pc);
                }
            }

            if (x.KeyList != null)
            {
                var keys = x.KeyList.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                foreach (string kid in keys)
                {
                    pk = new ProductKey { PID = x.ID, KID = int.Parse(kid) };
                    pkDAL.Insert(pk);
                }
            }
        }

        public List<Product> GetAllProduct()
        {
            return productDAL.SelectAll();
        }

        public void Delete(List<ProductListView> list)
        {
            list.ForEach(x =>
            {
                productDAL.Delete(x);
            });
        }

        public string GetKeyIDByPID(long pid)
        {
            var list = pkDAL.GetAllByPID(pid);
            var names = from xx in list select xx.KID;
            return string.Join(",", names);
        }
    }
}
